<?php


namespace app\api\controller;


use app\admin\model\GoodsCollect;
use app\common\controller\Api;
use think\Env;

class Collect extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    /**
     * 商品收藏显示
     *
     */
    public function index()
    {
        $page = input('page', 1);
        $collect = GoodsCollect::with('goods')
            ->where('user_id', $this->auth->id)
            ->page($page, 8)
            ->select();
        $count = GoodsCollect::where('user_id', $this->auth->id)
            ->count();
        $maxpage = ceil($count / 8);
        foreach ($collect as &$v) {
            $image = explode(',', $v['goods']['image']);
            if (isset($image[0])) {
                $v['goods']['image'] = Env::get('app.yuming') . $image[0];
            }
            //$v['goods_id'] = $v['goods']['id'];
            $v['goods_image'] = $v['goods']['image'];
            $v['goods_title'] = $v['goods']['title'];
            $v['goods_score'] = $v['goods']['score'];
            $v['goods_old_score'] = $v['goods']['old_score'];
            $v->unsetAppend();
            $v->unsetRelationAppend();
            unset($v['goods']);
            unset($v['createtime'], $v['updatetime']);
        }
        $data = ['count' => $count, 'maxpage' => $maxpage, 'collect' => $collect];
        $this->success('获取成功', $data);
    }


    /**
     * 商品收藏或取消收藏
     *
     */
    public function collect()
    {
        $goods = input('post.');
        if (empty($goods['goods_id'])) {
            $this->error('参数错误');
        }
        $model = new GoodsCollect();
        $a = GoodsCollect::where(['user_id' => $this->auth->id, 'goods_id' => $goods['goods_id']])->find();
        if (!empty($a)) {
            $data = GoodsCollect::destroy($a['id']);
            $this->success('取消收藏');
        } else {
            $model->user_id = $this->auth->id;
            $model->goods_id = $goods['goods_id'];
            $data = $model->save();
            $this->success('收藏成功');
        }

    }

    /**
     * 商品收藏删除
     *
     */
    public function delCollect()
    {
        $ids = input('ids');
        if (empty($ids)) {
            $this->error('请选中需要删除的商品');
        }
        if (GoodsCollect::where('id', 'in', $ids)->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}